#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update, COOPGIS_ReportLabStakerReport, COOPGIS_FormMisc
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings


def BuildLandmarkPolygonEditorForm(defaultmap, SpecialBuildFormInfo):
    from django.contrib import admin
    Dict={}
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([defaultmap.id, str(defaultmap.Name)[0:30]])
    Maps=Map.objects.all()
    for i in Maps:
        if(not i == defaultmap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    #Build LandmarkType List, use in both ChoiceFields (ensures duplication)
    TypeChoices=[]    
    if(SpecialBuildFormInfo['LandmarkType']):
        landmarktype=SpecialBuildFormInfo['LandmarkType']
        TypeChoices.append([landmarktype.id, landmarktype.Name[:30]])
    TypeChoices.append((-1, 'None Selected'))
    Types=LandmarkType.objects.all().exclude(PointIndicator=True).exclude(LineIndicator=True).filter(PolygonIndicator=True).order_by('Name')
    for i in Types:
        if(not[i.id, str(i.Name)[:30]] in TypeChoices):
            TypeChoices.append([i.id, str(i.Name)[:30]])

    Dict['LandmarkTypeSelection']=forms.ChoiceField(TypeChoices, required=False)
    Dict['LandmarkLandmarkTypeSelection']=forms.ChoiceField(TypeChoices, required=False)
    Dict['WKTPolygon']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    #LandmarkType Fields
    Dict['NewTypeIndicator']=forms.BooleanField(required=False)    
    Dict['UpdateTypeIndicator']=forms.BooleanField(required=False)
    Dict['DeleteTypeIndicator']=forms.BooleanField(required=False)
    Dict['Typeid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    Dict['TypeName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TypeDescription']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'30'}))
    #Landmark Fields
    Dict['NewLandmarkIndicator']=forms.BooleanField(required=False)
    Dict['UpdateLandmarkIndicator']=forms.BooleanField(required=False)
    Dict['DeleteLandmarkIndicator']=forms.BooleanField(required=False)
    Dict['Landmarkid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))    
    Dict['LandmarkName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['LandmarkDescription']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'30'}))
    return Dict
    
def ProcessLandmarkPolygonEditorForm(form, UserName):
    import models
    NewTypeIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewTypeIndicator')
    UpdateTypeIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateTypeIndicator')
    DeleteTypeIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeleteTypeIndicator')
    TypeName=COOPGIS_FormMisc.FormGetString(form, 'TypeName')
    TypeDescription=COOPGIS_FormMisc.FormGetString(form, 'TypeDescription')
    Typeid=COOPGIS_FormMisc.FormGetInteger(form, 'Typeid')

    NewLandmarkIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewLandmarkIndicator')
    UpdateLandmarkIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateLandmarkIndicator')
    DeleteLandmarkIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeleteLandmarkIndicator')
    LandmarkName=COOPGIS_FormMisc.FormGetString(form, 'LandmarkName')
    LandmarkDescription=COOPGIS_FormMisc.FormGetString(form, 'LandmarkDescription')
    Landmarkid=COOPGIS_FormMisc.FormGetInteger(form, 'Landmarkid')

    polygon = COOPGIS_FormMisc.FormGetGeometryFromWKT(form, 'WKTPolygon')
    LandmarkTypeSelection=COOPGIS_FormMisc.FormGetObjectFromid(form, 'LandmarkTypeSelection', LandmarkType)
    LandmarkLandmarkTypeSelection=COOPGIS_FormMisc.FormGetObjectFromid(form, 'LandmarkLandmarkTypeSelection', LandmarkType)
    LandmarkSelection=COOPGIS_FormMisc.FormGetObjectFromid(form, 'Landmarkid', LandmarkPolygon)
    command=Command()

    if(NewTypeIndicator):
        command=command.Create(Name='CreateLandmarkType', ObjectName=TypeName, Description=TypeDescription, 
                               PointIndicator=False, LineIndicator=False, PolygonIndicator=True, CommandUserName=UserName)
        LandmarkTypeSelection=command.Process()
    elif(UpdateTypeIndicator and Typeid):
        Objectid, ObjectIndexWhenReverseSorted=LandmarkTypeSelection.GetCommandidData()
        command=command.Create(Name='EditLandmarkType',  Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               ObjectName=TypeName, Description=TypeDescription, 
                               PointIndicator=False, LineIndicator=False, PolygonIndicator=True, CommandUserName=UserName)
        LandmarkTypeSelection=command.Process()
    elif(DeleteTypeIndicator and Typeid):
        landmarktype=geography.LandmarkType.objects.filter(id=Typeid)[0]
        if(LandmarkTypeSelection == landmarktype):
            LandmarkTypeSelection=None
        if(landmarktype.ResidesOnServerIndicator):
            command=command.Create(Name='DeleteLandmarkType', Objectid=landmarktype.id, CommandUserName=UserName)
            command.Process()
        else:
            landmarktype.CreateCommand.delete()
            landmarktype.delete()
    if(NewLandmarkIndicator):
        LandmarkTypeSelectionid, LandmarkTypeSelectionIndexWhenReverseSorted=LandmarkLandmarkTypeSelection.GetCommandidData()
        command=command.Create(Name='CreateLandmarkPolygon', ObjectName=LandmarkName, Description=LandmarkDescription, Polygon=polygon,
                               LandmarkTypeid=LandmarkTypeSelectionid, LandmarkTypeIndexWhenReverseSorted=LandmarkTypeSelectionIndexWhenReverseSorted,
                               CommandUserName=UserName)
        LandmarkSelection=command.Process()
    elif(UpdateLandmarkIndicator and Landmarkid):
        Objectid, ObjectIndexWhenReverseSorted=LandmarkSelection.GetCommandidData()
        LandmarkTypeSelectionid, LandmarkTypeSelectionIndexWhenReverseSorted=LandmarkLandmarkTypeSelection.GetCommandidData()
        if(not polygon):
            polygon=geography.LandmarkPolygon.objects.filter(id=Objectid)[0].Polygon

        command=command.Create(Name='EditLandmarkPolygon', Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               ObjectName=LandmarkName, Description=LandmarkDescription, Polygon=polygon, 
                               LandmarkTypeid=LandmarkTypeSelectionid, LandmarkTypeIndexWhenReverseSorted=LandmarkTypeSelectionIndexWhenReverseSorted,
                               CommandUserName=UserName)
        LandmarkSelection=command.Process()
    elif(DeleteLandmarkIndicator and Landmarkid):
        landmark=geography.LandmarkPolygon.objects.filter(id=Landmarkid)[0]
        if(LandmarkSelection == landmark):
            LandmarkSelection=None
        if(landmark.ResidesOnServerIndicator):
            command=command.Create(Name='DeleteLandmarkPolygon', Objectid=landmark.id, CommandUserName=UserName)
            command.Process()
        else:
            landmark.CreateCommand.delete()
            landmark.delete()
    return LandmarkTypeSelection, LandmarkSelection

def PopulateLandmarkPolygonEditorForm(form, LandmarkType, LandmarkPolygon):
    form.data['NewTypeIndicator']=False
    form.data['UpdateTypeIndicator']=False
    form.data['DeleteTypeIndicator']=False
    if(LandmarkType):
        form.setData({'LandmarkTypeSelection' : LandmarkType.id})
        form.data['TypeName']=LandmarkType.Name
        form.data['Typeid']=LandmarkType.id
        form.data['TypeDescription']=LandmarkType.Description

    form.data['NewLandmarkIndicator']=False
    form.data['UpdateLandmarkIndicator']=False
    form.data['DeleteLandmarkIndicator']=False
    if(LandmarkPolygon):
        form.setData({'LandmarkLandmarkTypeSelection': LandmarkPolygon.LandmarkType.id})
        form.data['LandmarkName']=LandmarkPolygon.Name
        form.data['Landmarkid']=LandmarkPolygon.id
        form.data['LandmarkDescription']=LandmarkPolygon.Description
        form.data['WKTPolygon']=str(LandmarkPolygon.Polygon)
    return form

def BuildLandmarkPointEditorForm(DefaultMap, SpecialBuildFormInfo):
    from django.contrib import admin
    Dict={}
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([DefaultMap.id, str(DefaultMap.Name)[0:30]])
    Maps=Map.objects.all().order_by('Name')
    for i in Maps:
        if(not i == DefaultMap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    #Build LandmarkType List, use in both ChoiceFields (ensures duplication)
    TypeChoices=[]    
    if(SpecialBuildFormInfo['LandmarkType']):
        landmarktype=SpecialBuildFormInfo['LandmarkType']
        TypeChoices.append([landmarktype.id, landmarktype.Name[:30]])
    TypeChoices.append((-1, 'None Selected'))
    Types=LandmarkType.objects.all().exclude(LineIndicator=True).exclude(PolygonIndicator=True).filter(PointIndicator=True).order_by('Name')
    for i in Types:
        if(not[i.id, str(i.Name)[:30]] in TypeChoices):
            TypeChoices.append([i.id, str(i.Name)[:30]])

    Dict['LandmarkTypeSelection']=forms.ChoiceField(TypeChoices, required=False)
    Dict['LandmarkLandmarkTypeSelection']=forms.ChoiceField(TypeChoices, required=False)
    Dict['WKTPoint']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))  
    #LandmarkType Fields
    Dict['NewTypeIndicator']=forms.BooleanField(required=False)    
    Dict['UpdateTypeIndicator']=forms.BooleanField(required=False)
    Dict['DeleteTypeIndicator']=forms.BooleanField(required=False)
    Dict['Typeid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    Dict['TypeName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TypeDescription']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'30'}))
    #Landmark Fields
    Dict['NewLandmarkIndicator']=forms.BooleanField(required=False)
    Dict['UpdateLandmarkIndicator']=forms.BooleanField(required=False)
    Dict['DeleteLandmarkIndicator']=forms.BooleanField(required=False)
    Dict['Landmarkid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))    
    Dict['LandmarkName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['LandmarkDescription']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'30'}))
    return Dict
    
def ProcessLandmarkPointEditorForm(form, UserName):
    import models
    NewTypeIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewTypeIndicator')
    UpdateTypeIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateTypeIndicator')
    DeleteTypeIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeleteTypeIndicator')
    TypeName=COOPGIS_FormMisc.FormGetString(form, 'TypeName')
    TypeDescription=COOPGIS_FormMisc.FormGetString(form, 'TypeDescription')
    Typeid=COOPGIS_FormMisc.FormGetInteger(form, 'Typeid')

    NewLandmarkIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewLandmarkIndicator')
    UpdateLandmarkIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateLandmarkIndicator')
    DeleteLandmarkIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeleteLandmarkIndicator')
    LandmarkName=COOPGIS_FormMisc.FormGetString(form, 'LandmarkName')
    LandmarkDescription=COOPGIS_FormMisc.FormGetString(form, 'LandmarkDescription')
    Landmarkid=COOPGIS_FormMisc.FormGetInteger(form, 'Landmarkid')
    point = COOPGIS_FormMisc.FormGetGeometryFromWKT(form, 'WKTPoint')
    LandmarkTypeSelection=COOPGIS_FormMisc.FormGetObjectFromid(form, 'LandmarkTypeSelection', LandmarkType)
    LandmarkLandmarkTypeSelection=COOPGIS_FormMisc.FormGetObjectFromid(form, 'LandmarkLandmarkTypeSelection', LandmarkType)
    LandmarkSelection=COOPGIS_FormMisc.FormGetObjectFromid(form, 'Landmarkid', LandmarkPoint)
    command=Command()

    if(NewTypeIndicator):
        command=command.Create(Name='CreateLandmarkType', ObjectName=TypeName, Description=TypeDescription, 
                               PointIndicator=True, LineIndicator=False, PolygonIndicator=False, CommandUserName=UserName)
        LandmarkTypeSelection=command.Process()
    elif(UpdateTypeIndicator and Typeid):
        Objectid, ObjectIndexWhenReverseSorted=LandmarkTypeSelection.GetCommandidData()
        command=command.Create(Name='EditLandmarkType',  Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               ObjectName=TypeName, Description=TypeDescription, 
                               PointIndicator=True, LineIndicator=False, PolygonIndicator=False, CommandUserName=UserName)
        LandmarkTypeSelection=command.Process()
    elif(DeleteTypeIndicator and Typeid):
        landmarktype=geography.LandmarkType.objects.filter(id=Typeid)[0]
        if(LandmarkTypeSelection == landmarktype):
            LandmarkTypeSelection=None
        if(landmarktype.ResidesOnServerIndicator):
            command=command.Create(Name='DeleteLandmarkType', Objectid=landmarktype.id, CommandUserName=UserName)
            command.Process()
        else:
            landmarktype.CreateCommand.delete()
            landmarktype.delete()
    if(NewLandmarkIndicator):
        LandmarkTypeSelectionid, LandmarkTypeSelectionIndexWhenReverseSorted=LandmarkLandmarkTypeSelection.GetCommandidData()
        command=command.Create(Name='CreateLandmarkPoint', ObjectName=LandmarkName, Description=LandmarkDescription, StartPoint=point,
                               LandmarkTypeid=LandmarkTypeSelectionid, LandmarkTypeIndexWhenReverseSorted=LandmarkTypeSelectionIndexWhenReverseSorted, 
                               CommandUserName=UserName)
        LandmarkSelection=command.Process()
    elif(UpdateLandmarkIndicator and Landmarkid):
        Objectid, ObjectIndexWhenReverseSorted=LandmarkSelection.GetCommandidData()
        LandmarkTypeSelectionid, LandmarkTypeSelectionIndexWhenReverseSorted=LandmarkLandmarkTypeSelection.GetCommandidData()
        if(not point):
            point=geography.LandmarkPoint.objects.filter(id=Objectid)[0].Point
        command=command.Create(Name='EditLandmarkPoint', Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               ObjectName=LandmarkName, Description=LandmarkDescription, StartPoint=point, 
                               LandmarkTypeid=LandmarkTypeSelectionid, LandmarkTypeIndexWhenReverseSorted=LandmarkTypeSelectionIndexWhenReverseSorted,
                               CommandUserName=UserName)
        LandmarkSelection=command.Process()
    elif(DeleteLandmarkIndicator and Landmarkid):
        landmark=geography.LandmarkPoint.objects.filter(id=Landmarkid)[0]
        if(LandmarkSelection == landmark):
            LandmarkSelection=None
        if(landmark.ResidesOnServerIndicator):
            command=command.Create(Name='DeleteLandmarkPoint', Objectid=landmark.id, CommandUserName=UserName)
            command.Process()
        else:
            landmark.CreateCommand.delete()
            landmark.delete()
    return LandmarkTypeSelection, LandmarkSelection

def PopulateLandmarkPointEditorForm(form, LandmarkType, LandmarkPoint):
    form.data['NewTypeIndicator']=False
    form.data['UpdateTypeIndicator']=False
    form.data['DeleteTypeIndicator']=False
    if(LandmarkType):
        form.setData({'LandmarkTypeSelection' : LandmarkType.id})
        form.data['TypeName']=LandmarkType.Name
        form.data['Typeid']=LandmarkType.id
        form.data['TypeDescription']=LandmarkType.Description

    form.data['NewLandmarkIndicator']=False
    form.data['UpdateLandmarkIndicator']=False
    form.data['DeleteLandmarkIndicator']=False
    if(LandmarkPoint):
        form.setData({'LandmarkLandmarkTypeSelection': LandmarkPoint.LandmarkType.id})
        form.data['LandmarkName']=LandmarkPoint.Name
        form.data['Landmarkid']=LandmarkPoint.id
        form.data['LandmarkDescription']=LandmarkPoint.Description
        form.data['WKTPoint']=str(Landmark.Point)
    else:
        form.data['WKTPoint']=''
    return form









def BuildLandmarkLineEditorForm(defaultmap, SpecialBuildFormInfo):
    from django.contrib import admin
    Dict={}
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([defaultmap.id, str(defaultmap.Name)[0:30]])
    Maps=Map.objects.all().order_by('Name')
    for i in Maps:
        if(not i == defaultmap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    #Build LandmarkType List, use in both ChoiceFields (ensures duplication)
    TypeChoices=[]    
    if(SpecialBuildFormInfo['LandmarkType']):
        landmarktype=SpecialBuildFormInfo['LandmarkType']
        TypeChoices.append([landmarktype.id, landmarktype.Name[:30]])
    TypeChoices.append((-1, 'None Selected'))
    Types=LandmarkType.objects.all().exclude(PointIndicator=True).exclude(PolygonIndicator=True).filter(LineIndicator=True).order_by('Name')
    for i in Types:
        if(not[i.id, str(i.Name)[:30]] in TypeChoices):
            TypeChoices.append([i.id, str(i.Name)[:30]])

    Dict['LandmarkTypeSelection']=forms.ChoiceField(TypeChoices, required=False)
    Dict['LandmarkLandmarkTypeSelection']=forms.ChoiceField(TypeChoices, required=False)

    Dict['WKTLine']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))
    #LandmarkType Fields
    Dict['NewTypeIndicator']=forms.BooleanField(required=False)    
    Dict['UpdateTypeIndicator']=forms.BooleanField(required=False)
    Dict['DeleteTypeIndicator']=forms.BooleanField(required=False)
    Dict['Typeid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    Dict['TypeName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TypeDescription']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'30'}))
    #Landmark Fields
    Dict['NewLandmarkIndicator']=forms.BooleanField(required=False)
    Dict['UpdateLandmarkIndicator']=forms.BooleanField(required=False)
    Dict['DeleteLandmarkIndicator']=forms.BooleanField(required=False)
    Dict['Landmarkid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))    
    Dict['LandmarkName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['LandmarkDescription']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'30'}))
    return Dict
    
def ProcessLandmarkLineEditorForm(form, UserName):
    import models
    NewTypeIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewTypeIndicator')
    UpdateTypeIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateTypeIndicator')
    DeleteTypeIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeleteTypeIndicator')
    TypeName=COOPGIS_FormMisc.FormGetString(form, 'TypeName')
    TypeDescription=COOPGIS_FormMisc.FormGetString(form, 'TypeDescription')
    Typeid=COOPGIS_FormMisc.FormGetInteger(form, 'Typeid')

    NewLandmarkIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewLandmarkIndicator')
    UpdateLandmarkIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateLandmarkIndicator')
    DeleteLandmarkIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeleteLandmarkIndicator')
    LandmarkName=COOPGIS_FormMisc.FormGetString(form, 'LandmarkName')
    LandmarkDescription=COOPGIS_FormMisc.FormGetString(form, 'LandmarkDescription')
    Landmarkid=COOPGIS_FormMisc.FormGetInteger(form, 'Landmarkid')
    line = COOPGIS_FormMisc.FormGetGeometryFromWKT(form, 'WKTLine')


    LandmarkTypeSelection=COOPGIS_FormMisc.FormGetObjectFromid(form, 'LandmarkTypeSelection', LandmarkType)
    LandmarkLandmarkTypeSelection=COOPGIS_FormMisc.FormGetObjectFromid(form, 'LandmarkLandmarkTypeSelection', LandmarkType)
    LandmarkSelection=COOPGIS_FormMisc.FormGetObjectFromid(form, 'Landmarkid', LandmarkLine)
    command=Command()

    if(NewTypeIndicator):
        command=command.Create(Name='CreateLandmarkType', ObjectName=TypeName, Description=TypeDescription, 
                               PointIndicator=False, LineIndicator=True, PolygonIndicator=False, CommandUserName=UserName)
        LandmarkTypeSelection=command.Process()
    elif(UpdateTypeIndicator and Typeid):
        Objectid, ObjectIndexWhenReverseSorted=LandmarkTypeSelection.GetCommandidData()
        command=command.Create(Name='EditLandmarkType',  Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               ObjectName=TypeName, Description=TypeDescription, 
                               PointIndicator=False, LineIndicator=True, PolygonIndicator=False, CommandUserName=UserName)
        LandmarkTypeSelection=command.Process()
    elif(DeleteTypeIndicator and Typeid):
        landmarktype=geography.LandmarkType.objects.filter(id=Typeid)[0]
        if(LandmarkTypeSelection == landmarktype):
            LandmarkTypeSelection=None
        if(landmarktype.ResidesOnServerIndicator):
            command=command.Create(Name='DeleteLandmarkType', Objectid=landmarktype.id, CommandUserName=UserName)
            command.Process()
        else:
            landmarktype.CreateCommand.delete()
            landmarktype.delete()
    if(NewLandmarkIndicator):
        LandmarkTypeSelectionid, LandmarkTypeSelectionIndexWhenReverseSorted=LandmarkLandmarkTypeSelection.GetCommandidData()
        command=command.Create(Name='CreateLandmarkLine', ObjectName=LandmarkName, Description=LandmarkDescription, Line=line,
                               LandmarkTypeid=LandmarkTypeSelectionid, LandmarkTypeIndexWhenReverseSorted=LandmarkTypeSelectionIndexWhenReverseSorted,
                               CommandUserName=UserName)
        LandmarkSelection=command.Process()
    elif(UpdateLandmarkIndicator and Landmarkid):
        Objectid, ObjectIndexWhenReverseSorted=LandmarkSelection.GetCommandidData()
        LandmarkTypeSelectionid, LandmarkTypeSelectionIndexWhenReverseSorted=LandmarkLandmarkTypeSelection.GetCommandidData()
        if(not line):
            line=geography.LandmarkLine.objects.filter(id=Objectid)[0].Line
        command=command.Create(Name='EditLandmarkLine', Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               ObjectName=LandmarkName, Description=LandmarkDescription, Line=line, 
                               LandmarkTypeid=LandmarkTypeSelectionid, LandmarkTypeIndexWhenReverseSorted=LandmarkTypeSelectionIndexWhenReverseSorted,
                               CommandUserName=UserName)
        LandmarkSelection=command.Process()
    elif(DeleteLandmarkIndicator and Landmarkid):
        landmark=geography.LandmarkLine.objects.filter(id=Landmarkid)[0]
        if(LandmarkSelection == landmark):
            LandmarkSelection=None
        if(landmark.ResidesOnServerIndicator):
            command=command.Create(Name='DeleteLandmarkLine', Objectid=landmark.id, CommandUserName=UserName)
            command.Process()
        else:
            landmark.CreateCommand.delete()
            landmark.delete()
    return LandmarkTypeSelection, LandmarkSelection

def PopulateLandmarkLineEditorForm(form, LandmarkType, LandmarkLine):
    form.data['NewTypeIndicator']=False
    form.data['UpdateTypeIndicator']=False
    form.data['DeleteTypeIndicator']=False
    if(LandmarkType):
        form.setData({'LandmarkTypeSelection' : LandmarkType.id})
        form.data['TypeName']=LandmarkType.Name
        form.data['Typeid']=LandmarkType.id
        form.data['TypeDescription']=LandmarkType.Description

    form.data['NewLandmarkIndicator']=False
    form.data['UpdateLandmarkIndicator']=False
    form.data['DeleteLandmarkIndicator']=False
    if(LandmarkLine):
        form.setData({'LandmarkLandmarkTypeSelection': LandmarkLine.LandmarkType.id})
        form.data['LandmarkName']=LandmarkLine.Name
        form.data['Landmarkid']=LandmarkLine.id
        form.data['LandmarkDescription']=LandmarkLine.Description
        form.data['WKTLine']=str(Landmark.Line)
    else:
        form.data['WKTLine']=''
    return form
